package com.edu.juc.completableFuture;

import java.util.concurrent.*;

/**
 * Future接口可以为主线程开一个分支任务，专门为主线程处理耗时和费力的复杂任务。
 * 对于简单的业务场景Future完全可以。
 */
public class FutureThreadPoolTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        long start = System.currentTimeMillis();

        FutureTask<String> task1 = new FutureTask<>(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "task1 over";
        });
        FutureTask<String> task2 = new FutureTask<>(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "task2 over";
        });

        FutureTask<String> task3 = new FutureTask<>(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "task3 over";
        });

        threadPool.submit(task1);
        threadPool.submit(task2);
        threadPool.submit(task3);
        // get 容易导致阻塞，一般建议放在程序后面，一旦调用不见不散，非要等到结果才会离开。
        System.out.println("task1.get() = " + task1.get());
        System.out.println("task2.get() = " + task2.get());
        // idDone 判断任务是否完成，false表示任务未完成，true表示任务已完成。 容易耗费CPU资源。
        while (!task3.isDone()) {
            System.out.println("task3.isDone() = " + task3.isDone());
        }
        System.out.println("task3.get() = " + task3.get());

        long end = System.currentTimeMillis();
        System.out.println("耗时：" + (end - start));

        threadPool.shutdown();
    }
}
